<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    <script>
        let username;
        let toName;

        //动态显示和谁聊天
        function showName(name){
            toName=name;
            //现在的聊天对话框
            $('#chatArea').css("display","online");
            //显示正在和谁聊天
            $("#charMsg").html("正在和<font face='谐体'>"+toName+"</font>聊天");

            // 清空聊天区
            $("msg").html('')

            //获取聊天记录
            let chatData=sessionStorage.getItem(toName);
            if (chatData!=null){
                //将聊天记录渲染到聊天区
                $("#msgs").html(chatData)
            }

        }
        //创建webSocket 对象
        let ws = new WebSocket("ws://localhost:8080/chat");
        //给 ws 绑定事件
        ws.onopen = function(){
            //显示在线信息
            $("userName").html("用户:"+username+"<span style='float:right;color: green'>在线</span>");
        };
        ws.onmessage = function (evt){
            //获取服务端推送过来的消息
            let dataStr = evt.data;
            let res = JSON.parse(dataStr);
            //判断是否是系统消息
            if (res.isSystem){
                //系统消息
                //1,好友列表展示

                //2,系统广播展示

            }else {
                //将服务器推送的消息进行展示
                let str = "";

                if (toName===res.fromName){
                    $("#msgs").append(str);
                }
                //存储接收的消息
                let chatData=sessionStorage.getItem(res.form);
                if (chatData!=null){
                    str=chatData +str;
                }

                sessionStorage.setItem(res.form,str);
            }
        };
        ws.onclose = function (){
            //显示离线信息
            $("userName").html("用户:"+res+"<span style='float:right;color: red'>离线</span>");
        };


        //发送消息
        $("#submit").click(function (){
            //获取输入内容
            let inputData=$("#context_text").val();
            //清空输入区
            $("#context_text").val("");
            let json = {"toNmae":toName,"message":inputData};

            //将数据展示给聊天区

            let str = "";
            $("#msgs").append(str)

            //存储发送的消息
            let chatData=sessionStorage.getItem(toName);
            if (chatData!=null){
                str=chatData +str;
            }

            sessionStorage.setItem(toName,str);
            //发送数据给服务器端
            ws.send(Json.stringify(json));
        })

        $(function (){
            $.ajax({
                url:"getUsername",
                success:function (res){
                    username=res;
                    $("userName").html("用户:"+res+"<span style='float:right;color: green'>在线</span>");
                },
                async:false
            });
        })
    </script>
</head>
<body>

</body>
</html>